package com.ruoyi.miniapp.controller;

import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.domain.MiniappMenu;
import com.ruoyi.miniapp.service.IMiniappMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 菜单权限Controller
 *
 * @author ruoyi
 * @date 2023-09-16
 */
@RestController
@RequestMapping("/menu")
public class MiniappMenuController extends BaseController
{
    @Autowired
    private IMiniappMenuService miniappMenuService;

    /**
     * 查询菜单权限列表
     */
    @RequiresPermissions("miniapp:menu:list")
    @GetMapping("/list")
    public AjaxResult list(MiniappMenu miniappMenu)
    {
        List<MiniappMenu> list = miniappMenuService.selectMiniappMenuList(miniappMenu);
        return success(list);
    }

    /**
     * 导出菜单权限列表
     */
    @RequiresPermissions("miniapp:menu:export")
    @Log(title = "菜单权限", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MiniappMenu miniappMenu)
    {
        List<MiniappMenu> list = miniappMenuService.selectMiniappMenuList(miniappMenu);
        ExcelUtil<MiniappMenu> util = new ExcelUtil<MiniappMenu>(MiniappMenu.class);
        util.exportExcel(response, list, "菜单权限数据");
    }

    /**
     * 获取菜单权限详细信息
     */
    @RequiresPermissions("miniapp:menu:query")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable("menuId") Long menuId)
    {
        return success(miniappMenuService.selectMiniappMenuByMenuId(menuId));
    }

    /**
     * 新增菜单权限
     */
    @RequiresPermissions("miniapp:menu:add")
    @Log(title = "菜单权限", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MiniappMenu miniappMenu)
    {
        if (!miniappMenuService.checkMenuNameUnique(miniappMenu))
        {
            return error("新增菜单'" + miniappMenu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(miniappMenu.getIsFrame()) && !StringUtils.ishttp(miniappMenu.getPath()))
        {
            return error("新增菜单'" + miniappMenu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        miniappMenu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(miniappMenuService.insertMiniappMenu(miniappMenu));
    }

    /**
     * 修改菜单权限
     */
    @RequiresPermissions("miniapp:menu:edit")
    @Log(title = "菜单权限", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MiniappMenu miniappMenu)
    {
        if (!miniappMenuService.checkMenuNameUnique(miniappMenu))
        {
            return error("修改菜单'" + miniappMenu.getMenuName() + "'失败，菜单名称已存在");
        }
        else if (UserConstants.YES_FRAME.equals(miniappMenu.getIsFrame()) && !StringUtils.ishttp(miniappMenu.getPath()))
        {
            return error("修改菜单'" + miniappMenu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        else if (miniappMenu.getMenuId().equals(miniappMenu.getParentId()))
        {
            return error("修改菜单'" + miniappMenu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        miniappMenu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(miniappMenuService.updateMiniappMenu(miniappMenu));
    }

    /**
     * 删除菜单权限
     */
    @RequiresPermissions("miniapp:menu:remove")
    @Log(title = "菜单权限", businessType = BusinessType.DELETE)
	@DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable Long menuId)
    {
        if (miniappMenuService.hasChildByMenuId(menuId))
        {
            return warn("存在子菜单,不允许删除");
        }
        if (miniappMenuService.checkMenuExistRole(menuId))
        {
            return warn("菜单已分配,不允许删除");
        }
        return toAjax(miniappMenuService.deleteMiniappMenuByMenuIds(menuId));
    }


    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(MiniappMenu miniMenu)
    {
        Long userId = SecurityUtils.getUserId();   //修改为uniapp的用户id
        List<MiniappMenu> menus = miniappMenuService.selectMenuList(miniMenu, userId);
        return success(miniappMenuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        Long userId = SecurityUtils.getUserId();
        List<MiniappMenu> menus = miniappMenuService.selectMenuList(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", miniappMenuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", miniappMenuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<MiniappMenu> menus = miniappMenuService.selectMenuTreeByUserId(userId);
        return success(miniappMenuService.buildMenus(menus));
    }
}
